package com.yh.cart.interceptor;

        import com.yh.cart.vo.UserInfoTo;
        import com.yh.common.constant.AuthServiceConstant;
        import com.yh.common.constant.CartConstant;
        import com.yh.common.vo.MemberRespVo;
        import org.springframework.stereotype.Component;
        import org.springframework.util.StringUtils;
        import org.springframework.web.servlet.HandlerInterceptor;
        import org.springframework.web.servlet.ModelAndView;

        import javax.servlet.http.Cookie;
        import javax.servlet.http.HttpServletRequest;
        import javax.servlet.http.HttpServletResponse;
        import javax.servlet.http.HttpSession;
        import java.util.UUID;

/**
 * 在执行目标方法之前，判断用户的登录状态。并进行封装，-》转递给controller目标的请求
 */
public class CartInterceptor  implements HandlerInterceptor{
    public static ThreadLocal<UserInfoTo> threadLocal=new ThreadLocal<>();

    /**
     * 目标方法执行前
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //封装了 userId 和 userKey
        UserInfoTo userInfoTo = new UserInfoTo();

        HttpSession session = request.getSession();
        MemberRespVo member = (MemberRespVo)session.getAttribute(AuthServiceConstant.LOGIN_USER);
        if(member!=null){
            //用户登录
            userInfoTo.setUserId(member.getId());
        }
        Cookie[] cookies = request.getCookies();
        if(cookies!=null&&cookies.length>0){
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                //说明有临时key
                if(name.equals(CartConstant.TEMP_USER_COOKIE_NAME)){
                    userInfoTo.setUserKey(cookie.getValue());
                    userInfoTo.setTempUserFlag(true);
                }
            }
        }

        //说明没有临时身份 ->分配一个
        if(StringUtils.isEmpty(userInfoTo.getUserKey())){
            String uuid = UUID.randomUUID().toString();
            userInfoTo.setUserKey(uuid);
        }

        //放行之前 将我们封装的数据进行保存
        threadLocal.set(userInfoTo);
        return true;
    }


    /**
     * 业务执行之后-》让浏览器保存cookie（一个月过期）
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = threadLocal.get();
        if(!userInfoTo.isTempUserFlag()){
            //代表没有临时用户身份 要保存一个临时身份
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
